package net.cl.utils;

import java.awt.Color;
import java.io.IOException;
import java.util.Random;

/**
 * 随机数工具类
 * 
 * @author CaoLei
 */
public class RandomUtil {
	
	private static final String[] WORDS = initRandomWords();

	private static String[] initRandomWords() {
		try {
			return FileUtil.read(PathUtil.getResourceFromRoot("resources/words.txt"), StringUtil.UTF8).split(
					StringUtil.SPACE);
		} catch (IOException e) {
			return new String[0];
		}
	}

	/**
	 * 返回0到i之间的随机数(包括0,i)
	 */
	public static int getRandomInt(int i) {
		Random random = new Random();
		return random.nextInt(i + 1);
	}

	/**
	 * 返回i到j之间的随机数(包括i,j)
	 */
	public static int getRandomInt(int i, int j) {
		Random random = new Random();
		return random.nextInt(j + 1 - i) + i;
	}

	/**
	 * 返回length位长度的随机字符串，该字符串全部由数字组成
	 */
	public static String getRandomNumber(int length) {
		if (length < 1)
			return StringUtil.EMPTY;
		Random random = new Random();
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < length; i++) {
			sb.append(random.nextInt(10));
		}
		return sb.toString();
	}

	/**
	 * 返回length位长度的随机字符串，该字符串由数字和字母组成
	 */
	public static String getRandomString(int length) {
		if (length < 1)
			return StringUtil.EMPTY;
		// 48~57数字
		// 65~90大写字母
		// 97~122小写字母
		StringBuilder sb = new StringBuilder();
		Random random = new Random();
		int r;
		while (sb.length() < length) {
			r = random.nextInt(122 + 1 - 48) + 48;
			if ((r >= 48 && r <= 57) || (r >= 65 && r <= 90) || (r >= 97 && r <= 122))
				sb.append((char) r);
		}
		return sb.toString();
	}

	/**
	 * 返回length位长度的随机单词
	 */
	public static String getRandomWords(int length) {
		if (length < 1)
			return StringUtil.EMPTY;
		StringBuilder sb = new StringBuilder();
		Random random = new Random();
		int i = 0;
		String s;
		while (i < length) {
			s = WORDS[random.nextInt(WORDS.length)];
			if (sb.indexOf(s) == -1) {
				if (i != 0)
					sb.append(StringUtil.SPACE);
				sb.append(s);
				i++;
			}
		}
		return sb.toString();
	}

	/**
	 * 产生随机颜色
	 */
	public static Color getRandomColor() {
		Random random = new Random();
		int r = random.nextInt(255);
		int g = random.nextInt(255);
		int b = random.nextInt(255);
		return new Color(r, g, b);
	}

}
